package com.midea.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @description：
 * @author: wangwl23
 * @create: 2021-08-08 18:41
 */
public class CasDemo {
    //总访问量
    static int count = 0;
    //模拟访问的方法
    //public static synchronized void request() throws InterruptedException {
    //在方法上加上synchronized的话，会极大影响效率
    //拓展：synchronized在方法上面，如果是静态方法，那么锁住的是class，属于类锁，放在成员方法上，也就是没用static修饰，那么就是对象锁
    public static void request() throws InterruptedException {
        //模拟耗时5秒钟
        TimeUnit.MILLISECONDS.sleep(5);
        count ++;
    }

    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        int threadSize = 100;
        CountDownLatch countDownLatch = new CountDownLatch(threadSize);
        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //模拟用户行为，每个用户访问10次网站；
                    try {
                        for (int j = 0; j < 10; j++) {
                            request();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
            thread.start();
        }
        //保证100个线程执行结束之后，在执行后面代码
        countDownLatch.await();
        long endTime = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + "耗时："+ (endTime-startTime) + ",count = " + count);
    }

}
